package com.cgy.bionimec.serviceimpl;

import com.cgy.bionimec.entity.Binghuan;
import com.cgy.bionimec.repository.BinghuanRespository;
import com.cgy.bionimec.service.BinghuanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.List;

@Service
public class BinghuanServiceImpl implements BinghuanService {
    @Autowired
    private BinghuanRespository binghuanRespository;

    @Override
    public Page<Binghuan> findAllBinghuan(Binghuan b, Pageable pageable) {
        return binghuanRespository.findAll(this.get(b), pageable);
    }

    @Override
    public Long findCoount() {
        return binghuanRespository.findCoount();
    }

    @Override
    public Binghuan insertOrUpdate(Binghuan binghuan) {
        return binghuanRespository.saveAndFlush(binghuan);
    }

    @Override
    public Integer deleteBinghuan(Integer id) {
        return binghuanRespository.deleteBinghuan(id);
    }

    @Override
    public Binghuan findBinghuanById(Integer id) {
        return binghuanRespository.findBinghuanById(id);
    }


    private Specification<Binghuan> get(Binghuan b) {
        return new Specification<Binghuan>() {
            @Override
            public Predicate toPredicate(Root<Binghuan> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.conjunction();
                List<Expression<Boolean>> expressions = predicate.getExpressions();

                if (b.getName() != null && b.getName() != "") {//用户名
                    expressions.add(criteriaBuilder.like(root.get("name"), "%" + b.getName() + "%"));
                }
                if(b.getCreattime()!=null&&b.getCreattime()!="") {
                    expressions.add(criteriaBuilder.like(root.get("creattime"), "%" + b.getCreattime() + "%"));
                }
                if(b.getEndtime()!=null&&b.getEndtime()!="") {
                    expressions.add(criteriaBuilder.like(root.get("endtime"), "%" + b.getEndtime() + "%"));
                }

                if (b.getKeshi()!= null && b.getKeshi() != "") {//科室
                    expressions.add(criteriaBuilder.like(root.get("keshi"), "%" + b.getKeshi() + "%"));
                }
                if (b.getSex()!= null && b.getSex() != "") {//性别
                    expressions.add(criteriaBuilder.like(root.get("sex"), "%" + b.getSex() + "%"));
                }
                return predicate;
            }
        };
    }
}
